package com.UnionPayCenter.distribution.manager.impl;

import com.UnionPayCenter.distribution.constants.DistributionConstants;
import com.UnionPayCenter.distribution.constants.SharePropDefaultConstants;
import com.UnionPayCenter.distribution.dto.SharePropModifyDTO;
import com.UnionPayCenter.distribution.entity.DistributionTemplateDO;
import com.UnionPayCenter.distribution.entity.SharePropDO;
import com.UnionPayCenter.distribution.manager.SharePropManager;
import com.UnionPayCenter.mapper.SharePropDOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Noah
 * @since 1.0.0, 2019/07/02
 */
@Service
public class SharePropManagerImpl implements SharePropManager {

    @Autowired
    private SharePropDOMapper sharePropDOMapper;

    /**
     * 分润初始化
     *
     * @param templateDO 模板信息
     */
    @Override
    public void initShareProp(DistributionTemplateDO templateDO) {
        SharePropDO sharePropDO = new SharePropDO();
        sharePropDO.setIdgen(String.valueOf(templateDO.getIdgen()));
        sharePropDO.setTotalLvl(SharePropDefaultConstants.TOTAL_LVL);
        sharePropDO.setFlag(SharePropDefaultConstants.FLAG);
        sharePropDO.setProp(SharePropDefaultConstants.PROP_FIRST);
        sharePropDO.setRemark(SharePropDefaultConstants.remark);
        sharePropDO.setLvl(SharePropDefaultConstants.FIRST_LVL);
        SharePropDO exists = sharePropDOMapper.selectByLvl(sharePropDO.getIdgen(), sharePropDO.getTotalLvl(), sharePropDO.getLvl());
        if (Objects.isNull(exists)) {
            sharePropDOMapper.insertSelective(sharePropDO);
        }
        sharePropDO.setPropIdgen(null);
        sharePropDO.setLvl(SharePropDefaultConstants.SECOND_LVL);
        sharePropDO.setProp(SharePropDefaultConstants.PROP_SECODE);
        exists = sharePropDOMapper.selectByLvl(sharePropDO.getIdgen(), sharePropDO.getTotalLvl(), sharePropDO.getLvl());
        if (Objects.isNull(exists)) {
            sharePropDOMapper.insertSelective(sharePropDO);
        }
    }

    /**
     * 分润初始化
     *
     * @param templateId 模板ID
     */
    @Override
    public List<SharePropDO> listByTemplateId(String templateId) {
        return sharePropDOMapper.listByTemplateId(templateId);
    }

    /**
     * 修改分润比例
     *
     * @param sharePropModifyDTO
     */
    @Override
    public void modifyShareProp(SharePropModifyDTO sharePropModifyDTO) {
        if (Objects.isNull(sharePropModifyDTO) || Objects.isNull(sharePropModifyDTO.getPropIdgen())) {
            return;
        }
        SharePropDO sharePropDO = new SharePropDO();
        sharePropDO.setLvl(sharePropModifyDTO.getLevel());
        sharePropDO.setPropIdgen(sharePropModifyDTO.getPropIdgen());
        sharePropDO.setProp(sharePropModifyDTO.getProp().divide(DistributionConstants.HUNDRED));
        sharePropDOMapper.updateByPrimaryKeySelective(sharePropDO);
    }
}
